<template>
  <div class="form-widget">
    <el-scrollbar :height="state.scrollHeight">
      <el-form class="form-body" :model="state.formData" :label-width="designer.formConfig.formLabelWidth">
        <draggable
          class="draggable"
          :sort="true"
          :list="designer.widgetList"
          item-key="id"
          v-bind="{ group: 'dragGroup', ghostClass: 'ghost', animation: 300 }"
          @end="onDragEnd"
          @add="(e) => onDragAdd(e)"
          @update="onDragUpdate"
          handle=".active-drag"
          :move="checkMove"
        >
          <template #item="{ element: widget, index }">
            <div class="move">
              <component
                v-model:options="widget.options"
                :is="getWidgetName(widget.type)"
                :widget="widget"
                :designer="designer"
                :key="widget.options.propName"
                :parent="designer"
                :index="index"
                @click.stop="selectWidget(widget, index)"
              ></component>
            </div>
          </template>
        </draggable>
      </el-form>
    </el-scrollbar>
  </div>
</template>
<script setup>
import { getWidgetName } from '@/utils/index.js'

import FieldComponents from '@/components/form-designer/form-widget/field-widget/index'
import { computed, inject, reactive, onMounted } from 'vue'
defineOptions({
  components: {
    ...FieldComponents,
  },
})
const designer = inject('designer')

const state = reactive({
  formData: computed(() => JSON.parse(designer.getJSON())),
  scrollHeight: 0,
})
const checkMove = (e) => {
  designer.checkFieldMove(e)
}
const onDragEnd = (e) => {
  console.log(e, 'onDragEnd')
}
const onDragAdd = (e) => {
  const { newIndex } = e
  designer.addNewWidgetToContainer()
  designer.selectedWidget.index = newIndex
}
const onDragUpdate = (e) => {
  designer.dragUpdate(e)
}
const selectWidget = (widget, index) => {
  designer.selectWidget(widget, index)
}
// 计算滚动条高度
const computedHeight = () => {
  state.scrollHeight = window.innerHeight - 75 + 'px'
}
onMounted(() => {
  window.addEventListener('resize', computedHeight)
})
</script>
<style lang="less" scoped>
.form-widget {
  position: relative;
  background: #f5f1f1;
  box-sizing: border-box;
  padding: 10px;
}
.form-ept {
  position: absolute;
  top: 0;
  right: 0;
  left: 0;
  bottom: 0;
}
.form-body {
  background: #fff;
  padding: 10px;
  .draggable {
    min-height: calc(100vh - 95px);
  }
}
</style>
